package com.tanqin.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.tanqin.constant.MessageConstant;
import com.tanqin.constant.RedisMessageConstant;
import com.tanqin.entity.Result;
import com.tanqin.pojo.Member;
import com.tanqin.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * 会员管理
 */
@RestController
@RequestMapping("/member")
public class MemberController {
    @Autowired
    JedisPool jedisPool;
    @Reference
    MemberService memberService;

    @PostMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map) {
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        // 获取 redis 中的验证码
        String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        // 比较验证码
        if (validateCode != null && validateCodeInRedis != null && validateCode.equals(validateCodeInRedis)) {
            // 验证码正确，判断是否为会员
            Member member = memberService.findByTelephone(telephone);
            if (member == null) {
                // 不是会员，自动完成注册
                member = new Member();
                // 为了保证时间的准确性，注册时间交给数据库设置
//                member.setRegTime(new Date());
                member.setPhoneNumber(telephone);
                memberService.add(member);
            }

            // 登录成功，向客户端写回 Cookie，内容为手机号
            Cookie cookie = new Cookie("login_member_telephone", telephone);
            // "/" 表示项目下所有请求都会携带 cookie
            cookie.setPath("/");
            cookie.setMaxAge(60 * 60 * 24 * 30);
            response.addCookie(cookie);

            // 将会员信息保存到 redis 中
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone, 60 * 30, json);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        } else {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
